#!/bin/bash

# Frps 自动安装配置脚本 (交互式)
# 支持系统：CentOS 7+/Debian 9+/Ubuntu 18.04+
# 版本：v2.0 (2025.07.30)

INSTALL_DIR="/usr/local/frps"
SERVICE_FILE="/etc/systemd/system/frps.service"

# 检查root权限
if [[ $EUID -ne 0 ]]; then
   echo "错误：此脚本必须以root权限运行" 
   exit 1
fi

# 获取最新版本
get_latest_version() {
    echo "正在获取最新版本..."
    LATEST_VERSION=$(curl -s https://api.github.com/repos/fatedier/frp/releases/latest | grep 'tag_name' | cut -d '"' -f 4 | sed 's/v//')
    if [[ -z "$LATEST_VERSION" ]]; then
        echo "错误：无法获取最新版本，使用默认版本 0.52.3"
        LATEST_VERSION="0.52.3"
    fi
    echo "最新版本: $LATEST_VERSION"
    FRP_VERSION=$LATEST_VERSION
}

# 检查系统架构
get_arch() {
    ARCH=$(uname -m)
    case $ARCH in
        x86_64)    ARCH="amd64" ;;
        aarch64|armv8l) ARCH="arm64" ;;
        armv7l)   ARCH="arm" ;;
        *)         echo "不支持的架构: $ARCH"; exit 1 ;;
    esac
}

# 安装依赖
install_dependencies() {
    if command -v yum &>/dev/null; then
        yum install -y wget tar curl
    elif command -v apt-get &>/dev/null; then
        apt-get update
        apt-get install -y wget tar curl
    else
        echo "警告：无法安装依赖，继续尝试..."
    fi
}

# 下载frp
download_frp() {
    DOWNLOAD_URL="https://ghfast.top/https://github.com/fatedier/frp/releases/download/v${FRP_VERSION}/frp_${FRP_VERSION}_linux_${ARCH}.tar.gz"
    echo "下载地址: $DOWNLOAD_URL"
    
    if ! wget --no-check-certificate -O /tmp/frp.tar.gz "$DOWNLOAD_URL"; then
        echo "错误：下载失败"
        exit 1
    fi
}

# 用户配置
get_user_config() {
    echo ""
    echo "============= Frps 配置 ============="
    read -p "输入绑定端口 [默认: 7000]: " BIND_PORT
    BIND_PORT=${BIND_PORT:-7000}
    
    read -p "启用仪表板? (y/n) [默认: y]: " ENABLE_DASHBOARD
    ENABLE_DASHBOARD=${ENABLE_DASHBOARD:-y}
    
    if [[ "$ENABLE_DASHBOARD" =~ ^[Yy]$ ]]; then
        read -p "仪表板端口 [默认: 7500]: " DASHBOARD_PORT
        DASHBOARD_PORT=${DASHBOARD_PORT:-7500}
        
        read -p "仪表板用户名 [默认: admin]: " DASHBOARD_USER
        DASHBOARD_USER=${DASHBOARD_USER:-admin}
        
        read -p "仪表板密码 [默认: frp@admin123]: " DASHBOARD_PWD
        DASHBOARD_PWD=${DASHBOARD_PWD:-frp@admin123}
    else
        DASHBOARD_PORT=""
    fi
    
    read -p "设置认证令牌 (token) [推荐设置]: " TOKEN
    TOKEN=${TOKEN:-your_secure_token_here}
    echo "====================================="
}

# 创建配置文件
create_config() {
    CONFIG_FILE="${INSTALL_DIR}/frps.ini"
    echo "创建配置文件..."
    
    cat > "$CONFIG_FILE" << EOF
[common]
bind_port = ${BIND_PORT}
EOF

    if [[ "$ENABLE_DASHBOARD" =~ ^[Yy]$ ]]; then
        cat >> "$CONFIG_FILE" << EOF
dashboard_port = ${DASHBOARD_PORT}
dashboard_user = ${DASHBOARD_USER}
dashboard_pwd = ${DASHBOARD_PWD}
EOF
    fi

    if [[ -n "$TOKEN" ]]; then
        echo "token = ${TOKEN}" >> "$CONFIG_FILE"
    fi
    
    echo -e "\n# 更多配置参考: https://gofrp.org/docs/" >> "$CONFIG_FILE"
    echo "配置文件已创建: $CONFIG_FILE"
}

# 安装frp
install_frp() {
    echo "正在安装 frps..."
    
    # 清理旧安装
    [[ -d "$INSTALL_DIR" ]] && rm -rf "$INSTALL_DIR"
    mkdir -p "$INSTALL_DIR"
    
    # 解压文件
    tar xzf /tmp/frp.tar.gz -C /tmp
    cd /tmp/frp_${FRP_VERSION}_linux_${ARCH} || exit
    cp frps "$INSTALL_DIR"
    rm -rf /tmp/frp*
}

# 创建系统服务
create_service() {
    cat > "$SERVICE_FILE" << EOF
[Unit]
Description=Frp Server Service
After=network.target

[Service]
Type=simple
User=nobody
Restart=on-failure
RestartSec=5s
ExecStart=${INSTALL_DIR}/frps -c ${INSTALL_DIR}/frps.ini
ExecReload=/bin/kill -s HUP \$MAINPID
LimitNOFILE=1048576

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
}

# 启用服务
enable_service() {
    read -p "是否启用开机自启和后台运行? (y/n) [默认: y]: " ENABLE_SERVICE
    ENABLE_SERVICE=${ENABLE_SERVICE:-y}
    
    if [[ "$ENABLE_SERVICE" =~ ^[Yy]$ ]]; then
        systemctl enable --now frps
        echo "服务已启用并启动"
    else
        echo "已跳过服务启用，请手动启动: ${INSTALL_DIR}/frps -c ${INSTALL_DIR}/frps.ini"
    fi
}

# 显示信息
show_info() {
    echo ""
    echo "================ 安装完成 ================"
    echo "Frps 版本: $FRP_VERSION"
    echo "安装目录: $INSTALL_DIR"
    echo "配置文件: ${INSTALL_DIR}/frps.ini"
    
    if [[ "$ENABLE_DASHBOARD" =~ ^[Yy]$ ]]; then
        IP=$(curl -s http://checkip.amazonaws.com || hostname -I | awk '{print $1}')
        echo "仪表板地址: http://${IP}:${DASHBOARD_PORT}"
        echo "用户名: $DASHBOARD_USER"
        echo "密码: $DASHBOARD_PWD"
    fi
    
    if [[ "$ENABLE_SERVICE" =~ ^[Yy]$ ]]; then
        echo "管理命令:"
        echo "  systemctl start frps      # 启动服务"
        echo "  systemctl stop frps       # 停止服务"
        echo "  systemctl restart frps    # 重启服务"
        echo "  systemctl status frps     # 查看状态"
    fi
    echo "=========================================="
    
    if [[ "$ENABLE_SERVICE" =~ ^[Yy]$ ]]; then
        sleep 2
        systemctl status frps --no-pager
    fi
}

# 主流程
main() {
    get_latest_version
    get_arch
    install_dependencies
    download_frp
    get_user_config
    install_frp
    create_config
    create_service
    enable_service
    show_info
}

main